<template>
  <div id="git-provider-edit">
    <el-form ref="gitForm" :model="gitForm" :rules="gitRules" label-width="100px">
      <el-form-item label="Git账号" prop="username">
        <el-input v-model="gitForm.username" :disabled="editType === 'edit'"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="gitForm.password" show-password></el-input>
      </el-form-item>
      <el-form-item label="是否默认使用">
        <el-switch
          v-model="gitForm.isDefault"
          active-text="是"
          inactive-text="否"
          active-value="1"
          inactive-value="0"
        />
      </el-form-item>
      <el-form-item label="是否全局使用">
        <el-switch
          v-model="gitForm.isGlobal"
          active-text="是"
          inactive-text="否"
          active-value="1"
          inactive-value="0"
        />
      </el-form-item>
      <el-form-item label="组件ID" prop="groupId">
        <el-input v-model="gitForm.groupId" :disabled="gitForm.isGlobal === '1'"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'GitProviderEdit',
  props: {
    gitProviderInfo: {
      type: Object,
      require: true,
      default: () => {
        return {}
      }
    },
    editType: {
      type: String,
      required: true,
      validator(val) {
        return ['edit', 'add'].includes(val)
      }
    }
  },
  emit: ['cancel-edit', 'submit-edit'],
  data() {
    return {
      gitForm: {
        username: '',
        password: '',
        isDefault: '',
        isGlobal: '',
        groupId: ''
      },
      gitRules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { min: 3, max: 32, message: '长度在 3 到 32 个字符', trigger: 'blur' }
        ],
        password: [{
          required: true, message: '密码不能为空', trigger: 'blur'
        }],
        groupId: [{
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!value && this.gitForm.isGlobal !== '1') {
              return callback(new Error('非全局凭证，组织ID不能为空'))
            }
            return callback()
          }
        }]
      }
    }
  },
  watch: {
    gitProviderInfo: {
      immediate: true,
      deep: true,
      handler(newVal) {
        this.gitForm = JSON.parse(JSON.stringify(newVal))
      }
    }
  },
  methods: {
    onSubmit() {
      this.$refs['gitForm'].validate((valid) => {
        if (valid) {
          this.$emit('submit-edit', this.gitForm)
        } else {
          return false
        }
      })
    },
    onCancel() {
      this.$emit('cancel-edit')
    }
  }
}
</script>

<style scoped>

</style>
